package jsyf.oa.service.wechat.service_account;

import com.alibaba.fastjson.JSONObject;
import jsyf.oa.entity.wechat.service_account.WechatOAuthTokenEntity;
import jsyf.oa.entity.wechat.service_account.WechatOAuthUserEntity;
import jsyf.oa.facade.wechat.config.WeChatConst;
import jsyf.oa.facade.wechat.service_account.WechatOAuthFacade;
import jsyf.oa.service.wechat.service_company.HttpUtil;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class WechatOAuthService implements WechatOAuthFacade {

    @Value("${wechat.serviceAccount.appId}")
    private String appId;

    @Value("${wechat.serviceAccount.appSecret}")
    private String appSecret;

    @Override
    public JSONObject getOAuthTokenEntity(String code) {

        // 拼接请求地址
        String requestUrl = WeChatConst.get_oauth2_token_byCode;
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        JSONObject jsonObject = HttpUtil.request(requestUrl, "GET", null);
        return jsonObject;
    }

    @Override
    public JSONObject getOAuthUserEntity(String accessToken, String openId) {
        // 拼接请求地址
        String requestUrl = WeChatConst.get_oauth2_user;
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        JSONObject jsonObject = HttpUtil.request(requestUrl, "GET", null);

        return jsonObject;
    }
}
